//
//  AreaPickView.m
//  BuyDemo
//
//  Created by liuyanfang on 16/6/27.
//  Copyright © 2016年 ccc. All rights reserved.
//

#import "AreaPickView.h"

@implementation AreaPickView
{
    UIView *view;
    UIPickerView *picker;
    NSMutableArray *areaArr;
    NSMutableArray *dataArr;
    NSMutableArray *provinceArr;
    NSArray *provinceDataArr;
    NSMutableArray *_cityArr;
    NSArray *_cityDataArr;
    NSMutableArray *_subCityArr;
    NSArray *_subCityDataArr;
}
@synthesize cancelbtn,surebtn;
- (id)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor whiteColor];
        self.userInteractionEnabled = YES;
        self.layer.borderColor = [UIColor clearColor].CGColor;
        self.layer.borderWidth =  1;
        [self.layer setMasksToBounds:YES];
        
        cancelbtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [cancelbtn addTarget:self action:@selector(cancelBtn:) forControlEvents:UIControlEventTouchUpInside];
        [cancelbtn setTitle:@"取消" forState:0];
        cancelbtn.titleLabel.font = [UIFont systemFontOfSize:14];
        cancelbtn.tag = 1;
        cancelbtn.frame = CGRectMake(10, 5, 40, 35);
        [cancelbtn setTitleColor:[UIColor lightGrayColor] forState:0];
        [cancelbtn.layer setMasksToBounds:YES];
        [self addSubview:cancelbtn];
        
        surebtn = [UIButton buttonWithType:UIButtonTypeSystem];
        [surebtn addTarget:self action:@selector(selectbtn:) forControlEvents:UIControlEventTouchUpInside];
        [surebtn setTitle:@"完成" forState:0];
        surebtn.tag = 2;
        cancelbtn.titleLabel.font = [UIFont systemFontOfSize:14];
        surebtn.frame = CGRectMake(CGRectGetWidth(frame)-50, 5, 40, 35);
        [self addSubview:surebtn];
        
        picker = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 30, CGRectGetWidth(frame), CGRectGetHeight(frame)-50)];
        
        picker.delegate  = self;
        picker.dataSource = self;
        picker.showsSelectionIndicator = YES;
        
        NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"AreaPlist" ofType:@"plist"];
        dataArr = [[NSMutableArray alloc] initWithContentsOfFile:plistPath];
        
        areaArr = [[NSMutableArray alloc] initWithCapacity:0];
        
        provinceArr = [[NSMutableArray alloc] initWithCapacity:0];
        
        _cityArr = [[NSMutableArray alloc] initWithCapacity:0];
        
        _subCityArr = [[NSMutableArray alloc] initWithCapacity:0];
        
        for (NSDictionary *dic in dataArr) {
            NSString *areaStr  =   [dic objectForKey:@"region"];
            
            [areaArr addObject:areaStr];
            
        }
        
        [self addSubview:picker];
    }
    return self;
}
- (void)cancelBtn:(UIButton *)sender{
    if ([self.delegate respondsToSelector:@selector(cancelBtn)]) {
        [self.delegate cancelBtn];
    }
    [self dismmis];
}
- (void)selectbtn:(UIButton *)sender{
    NSInteger rowOne = [picker selectedRowInComponent:0];
    NSInteger rowTwo = [picker selectedRowInComponent:1];
    NSInteger rowThree = [picker selectedRowInComponent:2];
    NSInteger rowFour = [picker selectedRowInComponent:3];
    NSString *areaString = @"";
    NSString *provinceString= @"";
    NSString *cityString = @"";
    NSString *citySub = @"";

    if (rowOne<areaArr.count) {
        areaString = areaArr[rowOne];
    }
    if (rowTwo<provinceArr.count) {
        provinceString = provinceArr[rowTwo];
    }
    if (rowThree<_cityArr.count) {
        cityString = _cityArr[rowThree];
    }
    if (rowFour<_subCityArr.count) {
        citySub = _subCityArr[rowFour];
    }
    NSString *areaName = [NSString stringWithFormat:@"%@ - %@ - %@",provinceString,cityString,citySub];

    if ([self.delegate respondsToSelector:@selector(pickerDidSelectName:)]) {
        [self.delegate pickerDidSelectName:areaName];
    }
    [self dismmis];
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 4;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    if (component==0) {
      return areaArr.count;
    }
    if (component==1) {
        [provinceArr removeAllObjects];
        NSInteger selectIndex = [picker selectedRowInComponent:0];
        
        if (selectIndex<dataArr.count) {
            NSDictionary *dic = dataArr[selectIndex];
            NSArray *arr = [dic objectForKey:@"provinces"];
            for (NSDictionary *dict in arr) {
                NSString *str = [dict objectForKey:@"province"];
                [provinceArr addObject:str];
            }
            provinceDataArr = arr;
            return provinceArr.count;
        }
    }
    if (component==2) {
        [_cityArr removeAllObjects];
        NSInteger provinceSelect = [picker selectedRowInComponent:1];
        
        if (provinceSelect<provinceArr.count) {
            NSDictionary *cityDic = provinceDataArr[provinceSelect];
            
            NSArray *arr = [cityDic objectForKey:@"cities"];
            
            for (NSDictionary *dict in arr) {
                NSString *str = [dict objectForKey:@"city"];
                
                [_cityArr addObject:str];
            }
            _cityDataArr =arr;
        }
        
        return _cityArr.count;
    }
    if (component==3) {
        [_subCityArr removeAllObjects];
        NSInteger citySelect = [picker selectedRowInComponent:2];
        
        if (citySelect<_cityArr.count) {
            NSDictionary *currentArea = _cityDataArr[citySelect];
            NSArray *arr = [currentArea objectForKey:@"areas"];
            for (NSString *areaStr in arr) {
                
                [_subCityArr addObject:areaStr];
            }
        }
        return _subCityArr.count;
    }
    return 0;
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    
    if (component==0) {
        if (row<areaArr.count) {
             return areaArr[row];   
        }
    }
    if (component==1) {

        if (row<provinceArr.count) {
            return provinceArr[row];
        }
    }
    if (component==2) {
        
        if (row<_cityArr.count) {
            return _cityArr[row];
        }

    }
    if (component==3) {
        
        if (row<_subCityArr.count) {
            return _subCityArr[row];
        }
        
    }
    return nil;
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    
    if (component==0) {
        [picker reloadComponent:1];
        [picker selectRow:0 inComponent:1 animated:YES];
        [picker reloadComponent:2];
        [picker selectRow:0 inComponent:2 animated:YES];
        [picker reloadComponent:3];
        [picker selectRow:0 inComponent:3 animated:YES];
    }
    if (component==1) {
        [picker reloadComponent:2];
        [picker selectRow:0 inComponent:2 animated:YES];
        [picker reloadComponent:3];
        [picker selectRow:0 inComponent:3 animated:YES];

    }
    if (component==2) {
        [picker reloadComponent:3];
        [picker selectRow:0 inComponent:3 animated:NO];
    }
}
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
    UILabel *pickLabel;
    if (!pickLabel) {
        pickLabel = [[UILabel alloc] init];
        pickLabel.font = [UIFont systemFontOfSize:14];
        pickLabel.backgroundColor = [UIColor clearColor];
        pickLabel.text = [self pickerView:pickerView titleForRow:row forComponent:component];
    }
    return pickLabel;
}
-(void)show
{
    UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
    view = [[UIView alloc] initWithFrame:keyWindow.bounds];
    view.alpha = 0.3;
    view.backgroundColor = [UIColor blackColor];
    [keyWindow addSubview:view];
    
    self.alpha = 1;
    [keyWindow addSubview:self];
    [keyWindow bringSubviewToFront:self];
    
    CAKeyframeAnimation *bounceAnimation = [CAKeyframeAnimation animation];
    bounceAnimation.duration = 0.3;
    bounceAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
    bounceAnimation.values = [NSArray arrayWithObjects:
                              [NSNumber numberWithFloat:0.01],
                              [NSNumber numberWithFloat:1.1],
                              [NSNumber numberWithFloat:0.9],
                              [NSNumber numberWithFloat:1.0],
                              nil];
    
    [self.layer addAnimation:bounceAnimation forKey:@"transform.scale"];
}

//消失
-(void)dismmis
{
    [UIView animateWithDuration:0.25
                          delay:0.0
                        options:UIViewAnimationOptionCurveEaseInOut
                     animations:^
     {
         self.transform = CGAffineTransformConcat(self.transform, CGAffineTransformMakeScale(0.01, 0.01));
         view.alpha = 0;
     }
                     completion:^(BOOL finished)
     {
         [view removeFromSuperview];
         [self removeFromSuperview];
         
     }];
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
